package com;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.support.BasicAuthorizationInterceptor;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

/**
 * @Description: 微服务项目1
 * @EnableCircuitBreaker : 开启断路器 当对特定服务的呼叫达到一定阈值时（Hystrix中的默认值为5秒内的20次故障，
 *                       电路打开，不进行通话。在错误和开路的情况下, 开发人员可以提供后备预防方案
 *                       可参考HystrixTest类中代码
 * @author hp
 * @date 2017年7月16日 上午9:37:59
 */
@SpringBootApplication
@EnableCircuitBreaker // 开启断路器
@EnableDiscoveryClient
@RefreshScope
public class SpringCloudClientApplication {
	
	@Bean
	@LoadBalanced
	public RestTemplate restTemplate() {
		RestTemplate restTemplate = new RestTemplate();
		// 配置访问微服务账号密码
		List<ClientHttpRequestInterceptor> list = new ArrayList<ClientHttpRequestInterceptor>();
		list.add(new BasicAuthorizationInterceptor("hp", "hp"));
		restTemplate.setInterceptors(list);
		
		// 配置字符集
		List<HttpMessageConverter<?>> msgList = restTemplate.getMessageConverters();
		for (HttpMessageConverter<?> converter : msgList) {
			if (converter instanceof StringHttpMessageConverter) {
				((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
				break;
			}
		}
		
		return restTemplate;
	}

	public static void main(String[] args) throws Exception {
		SpringApplication.run(SpringCloudClientApplication.class, args);
	}
	
}